<template>
  <view class="home-page">
    <!-- 选项卡导航 -->
    <view class="tab-nav">
      <view
        v-for="(tab, index) in tabs"
        :key="index"
        :class="['tab-item', currentTab === index ? 'active' : '']"
        @click="switchTab(index)"
      >
        {{ tab.title }}
      </view>
    </view>

    <!-- 内容展示区域 -->
    <view class="preview-area">
      <!-- 定额不一致板块 -->
      <view v-if="currentTab === 0" class="preview-section">
        <text class="section-title">定额不一致</text>
        <view v-if="overList.length === 0" class="empty-message">
          暂无超限记录
        </view>
        <view v-else class="table-wrapper">
          <table class="data-table">
            <thead>
              <tr>
                <th>序号</th>
                <th>定额编码</th>
                <th>差异类型</th>
                <th>材料项目</th>
                <th>标准项目</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, idx) in overList" :key="idx">
                <td>{{ idx + 1 }}</td>
                <td>{{ item.de_id }}</td>
                <td>{{ item.diffType }}</td>
                <td>{{ item.wrong }}</td>
                <td>{{ item.stand }}</td>
              </tr>
            </tbody>
          </table>
        </view>
      </view>

      <!-- 用量清单板块 -->
      <view v-if="currentTab === 1" class="preview-section">
        <text class="section-title">用量清单</text>
        <view v-if="usageList.length === 0" class="empty-message">
          暂无用量数据
        </view>
        <view v-else class="table-wrapper">
          <table class="data-table">
            <thead>
              <tr>
                <th>序号</th>
                <th>定额编码</th>
                <th>定额名称</th>
                <th>标准用量</th>
                <th>单位</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, idx) in usageList" :key="idx">
                <td>{{ idx + 1 }}</td>
                <td>{{ item.de_id }}</td>
                <td>{{ item.de_name }}</td>
                <td>{{ item.standUsage }}</td>
                <td>{{ item.unit }}</td>
              </tr>
            </tbody>
          </table>
        </view>
      </view>

      <!-- 机械使用费板块 -->
      <view v-if="currentTab === 2" class="preview-section">
        <text class="section-title">机械使用费</text>
        <view v-if="machineryFees.length === 0" class="empty-message">
          暂无机械使用费数据
        </view>
        <view v-else class="table-wrapper">
          <table class="data-table">
            <thead>
              <tr>
                <th>序号</th>
                <th>机械名称</th>
                <th>规格型号</th>
                <th>使用时间</th>
                <th>单位</th>
                <th>单价</th>
                <th>合计</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, idx) in machineryFees" :key="idx">
                <td>{{ idx + 1 }}</td>
                <td>{{ item.name }}</td>
                <td>{{ item.specification }}</td>
                <td>{{ item.usageTime }}</td>
                <td>{{ item.unit }}</td>
                <td>{{ item.unitPrice }}</td>
                <td>{{ item.totalPrice }}</td>
              </tr>
            </tbody>
          </table>
        </view>
      </view>

      <!-- 仪表使用费板块 -->
      <view v-if="currentTab === 3" class="preview-section">
        <text class="section-title">仪表使用费</text>
        <view v-if="instrumentFees.length === 0" class="empty-message">
          暂无仪表使用费数据
        </view>
        <view v-else class="table-wrapper">
          <table class="data-table">
            <thead>
              <tr>
                <th>序号</th>
                <th>仪表名称</th>
                <th>规格型号</th>
                <th>使用时间</th>
                <th>单位</th>
                <th>单价</th>
                <th>合计</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, idx) in instrumentFees" :key="idx">
                <td>{{ idx + 1 }}</td>
                <td>{{ item.name }}</td>
                <td>{{ item.specification }}</td>
                <td>{{ item.usageTime }}</td>
                <td>{{ item.unit }}</td>
                <td>{{ item.unitPrice }}</td>
                <td>{{ item.totalPrice }}</td>
              </tr>
            </tbody>
          </table>
        </view>
      </view>

      <!-- 甲供材料板块 -->
      <view v-if="currentTab === 4" class="preview-section">
        <text class="section-title">甲供材料</text>
        <view v-if="supplierAMaterials.length === 0" class="empty-message">
          暂无甲供材料数据
        </view>
        <view v-else class="table-wrapper">
          <table class="data-table">
            <thead>
              <tr>
                <th>序号</th>
                <th>材料名称</th>
                <th>规格型号</th>
                <th>数量</th>
                <th>单位</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, idx) in supplierAMaterials" :key="idx">
                <td>{{ item.id }}</td>
                <td>{{ item.mat_name }}</td>
                <td>{{ item.mat_type }}</td>
                <td>{{ item.mat_count }}</td>
                <td>{{ item.mat_unit }}</td>
              </tr>
            </tbody>
          </table>
        </view>
      </view>

      <!-- 乙供材料板块 -->
      <view v-if="currentTab === 5" class="preview-section">
        <text class="section-title">乙供材料</text>
        <view v-if="supplierBMaterials.length === 0" class="empty-message">
          暂无乙供材料数据
        </view>
        <view v-else class="table-wrapper">
          <table class="data-table">
            <thead>
              <tr>
                <th>序号</th>
                <th>材料名称</th>
                <th>规格型号</th>
                <th>数量</th>
                <th>单位</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, idx) in supplierBMaterials" :key="idx">
                <td>{{ item.id }}</td>
                <td>{{ item.mat_name }}</td>
                <td>{{ item.mat_type }}</td>
                <td>{{ item.mat_count }}</td>
                <td>{{ item.mat_unit }}</td>
              </tr>
            </tbody>
          </table>
        </view>
      </view>

      <!-- 其他费用板块 -->
      <view v-if="currentTab === 6" class="preview-section">
        <text class="section-title">其他费用</text>
        <view v-if="otherFees.length === 0" class="empty-message">
          暂无其他费用数据
        </view>
        <view v-else class="table-wrapper">
          <table class="data-table">
            <thead>
              <tr>
                <th>序号</th>
                <th>费用名称</th>
                <th>费用类型</th>
                <th>金额</th>
                <th>单位</th>
                <th>备注</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, idx) in otherFees" :key="idx">
                <td>{{ idx + 1 }}</td>
                <td>{{ item.name }}</td>
                <td>{{ item.type }}</td>
                <td>{{ item.amount }}</td>
                <td>{{ item.unit }}</td>
                <td>{{ item.remark }}</td>
              </tr>
            </tbody>
          </table>
        </view>
      </view>

      <!-- 历史验收记录板块 -->
      <view v-if="currentTab === 7" class="preview-section">
        <text class="section-title">历史验收记录</text>
        <view v-if="historyProblems.length === 0" class="empty-message">
          暂无验收记录
        </view>
        <view v-else>
          <view
            v-for="(group, index) in groupedProblems"
            :key="index"
            class="type-group"
          >
            <text class="type-header">第{{ group.type }}次验收</text>
            <view class="history-list">
              <view v-if="group.items.length === 0" class="empty-message">
                暂无历史问题记录
              </view>
              <view v-else>
                <view
                  v-for="(item, idx) in group.items"
                  :key="idx"
                  class="problem-item"
                >
                  <view class="problem-header">
                    <view class="acc-person">
                      验收人: {{ item.accPerson }}
                    </view>
                    <view class="acc-date">{{ item.accDate }}</view>
                  </view>
                  <view class="problem-content">
                    {{ item.accProblem }}
                  </view>
                  <!-- 调整地图样式 -->
                  <map
                    :latitude="item.lat"
                    :longitude="item.lng"
                    :markers="[
                      {
                        id: idx,
                        latitude: item.lat,
                        longitude: item.lng,
                        width: 30,
                        height: 30,
                        iconPath: '/static/location.png',
                      }
                    ]"
                    style="width: 100%; height: 150px; margin-top: 12px;"
                  ></map>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";

const emit = defineEmits(["parsed"]);
const token = uni.getStorageSync("userInfo").token;

// 原有数据
const overList = ref([]);
const usageList = ref([]);
const historyProblems = ref([]);

// 新增数据
const supplierAMaterials = ref([]);
const supplierBMaterials = ref([]);
const machineryFees = ref([]);
const instrumentFees = ref([]);
const otherFees = ref([]);

// 当前的 misId 和 taskId，用于拉取各类数据
const currentMisId = ref("");
const currentTaskId = ref("");

// 选项卡配置 - 按照要求的顺序排列
const tabs = ref([
  { title: "定额不一致", key: "overLimits" },
  { title: "用量清单", key: "usageList" },
  { title: "机械使用费", key: "machineryFees" },
  { title: "仪表使用费", key: "instrumentFees" },
  { title: "甲供材料", key: "supplierAMaterials" },
  { title: "乙供材料", key: "supplierBMaterials" },
  { title: "其他费用", key: "otherFees" },
  { title: "历史验收情况", key: "historyProblems" },
]);

// 当前选中的选项卡索引
const currentTab = ref(0);

// 按 type 字段分组计算属性（历史问题）
const groupedProblems = computed(() => {
  const groups = {};
  historyProblems.value.forEach((item) => {
    if (!groups[item.type]) {
      groups[item.type] = { type: item.type, items: [] };
    }
    groups[item.type].items.push(item);
  });
  // 按 type 升序排序
  return Object.values(groups).sort((a, b) => a.type - b.type);
});

/**
 * 切换选项卡
 */
function switchTab(index) {
  currentTab.value = index;
  // 切换选项卡时重新加载对应数据（可根据需求调整）
  loadDataByTab(tabs.value[index].key);
}

/**
 * 根据选项卡加载对应数据
 */
function loadDataByTab(tabKey) {
  if (!currentMisId.value || !currentTaskId.value) return;

  switch (tabKey) {
    case "overLimits":
      fetchOverLimitsData(currentMisId.value, currentTaskId.value);
      break;
    case "usageList":
      fetchUsageListData(currentMisId.value, currentTaskId.value);
      break;
    case "machineryFees":
      fetchMachineryFeesData(currentMisId.value, currentTaskId.value);
      break;
    case "instrumentFees":
      fetchInstrumentFeesData(currentMisId.value, currentTaskId.value);
      break;
    case "otherFees":
      fetchOtherFeesData(currentMisId.value, currentTaskId.value);
      break;
    case "historyProblems":
      fetchHistoryProblems(currentMisId.value, currentTaskId.value);
      break;
    case "supplierAMaterials":
      fetchSupplierAMaterials(currentMisId.value, currentTaskId.value);
      break;
    case "supplierBMaterials":
      fetchSupplierBMaterials(currentMisId.value, currentTaskId.value);
      break;
  }
}

/**
 * 原有数据请求函数
 */
function fetchOverLimitsData(misId, taskId) {
  uni.request({
    url: `./api/overLimits?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        overList.value = res.data;
      } else {
        console.error("获取定额不一致数据失败：", res);
        overList.value = [];
      }
    },
    fail: (err) => {
      console.error("网络请求出错（overLimits）：", err);
      overList.value = [];
    },
  });
}

function fetchUsageListData(misId, taskId) {
  uni.request({
    url: `./api/usageList?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        usageList.value = res.data;
      } else {
        // console.error("获取用量清单数据失败：", res);
        usageList.value = [];
      }
    },
    fail: (err) => {
      // console.error("网络请求出错（usageList）：", err);
      usageList.value = [];
    },
  });
}

function fetchHistoryProblems(misId, taskId) {
  if (!misId || !taskId) {
    historyProblems.value = [];
    return;
  }

  uni.request({
    url: `./api/historyProblems?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        historyProblems.value = res.data;
      } else {
        uni.showToast({ title: "加载历史问题失败", icon: "none" });
        historyProblems.value = [];
      }
    },
    fail: () => {
      uni.showToast({ title: "网络异常，无法加载历史问题", icon: "none" });
      historyProblems.value = [];
    },
  });
}

/**
 * 新增数据请求函数
 */
function fetchSupplierAMaterials(misId, taskId) {
  uni.request({
    url: `./api/jgmat?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        supplierAMaterials.value = res.data;
      } else {
        console.error("获取甲供材料数据失败：", res);
        supplierAMaterials.value = [];
      }
    },
    fail: (err) => {
      console.error("网络请求出错（supplierAMaterials）：", err);
      supplierAMaterials.value = [];
    },
  });
}

function fetchSupplierBMaterials(misId, taskId) {
  uni.request({
    url: `./api/ygmat?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        supplierBMaterials.value = res.data;
      } else {
        console.error("获取乙供材料数据失败：", res);
        supplierBMaterials.value = [];
      }
    },
    fail: (err) => {
      console.error("网络请求出错（supplierBMaterials）：", err);
      supplierBMaterials.value = [];
    },
  });
}

function fetchMachineryFeesData(misId, taskId) {
  uni.request({
    url: `./api/machineryFees?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        machineryFees.value = res.data;
      } else {
        console.error("获取机械使用费数据失败：", res);
        machineryFees.value = [];
      }
    },
    fail: (err) => {
      console.error("网络请求出错（machineryFees）：", err);
      machineryFees.value = [];
    },
  });
}

function fetchInstrumentFeesData(misId, taskId) {
  uni.request({
    url: `./api/instrumentFees?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        instrumentFees.value = res.data;
      } else {
        console.error("获取仪表使用费数据失败：", res);
        instrumentFees.value = [];
      }
    },
    fail: (err) => {
      console.error("网络请求出错（instrumentFees）：", err);
      instrumentFees.value = [];
    },
  });
}

function fetchOtherFeesData(misId, taskId) {
  uni.request({
    url: `./api/otherFees?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: {
      Authorization: `Bearer ${token}`,
    },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        otherFees.value = res.data;
      } else {
        console.error("获取其他费用数据失败：", res);
        otherFees.value = [];
      }
    },
    fail: (err) => {
      console.error("网络请求出错（otherFees）：", err);
      otherFees.value = [];
    },
  });
}

function onFetchSiblingData(payload) {
  currentMisId.value = payload.misId;
  currentTaskId.value = payload.taskId;

  // 加载所有数据（也可以优化为只加载当前选项卡数据）
  fetchOverLimitsData(payload.misId, payload.taskId);
  fetchUsageListData(payload.misId, payload.taskId);
  fetchHistoryProblems(payload.misId, payload.taskId);
  fetchSupplierAMaterials(payload.misId, payload.taskId);
  fetchSupplierBMaterials(payload.misId, payload.taskId);
  fetchMachineryFeesData(payload.misId, payload.taskId);
  fetchInstrumentFeesData(payload.misId, payload.taskId);
  fetchOtherFeesData(payload.misId, payload.taskId);
}

onMounted(() => {
  uni.$on("fetchSiblingData", onFetchSiblingData);
});

onUnmounted(() => {
  uni.$off("fetchSiblingData", onFetchSiblingData);
});
</script>

<style scoped>
/* -------------------- */
/* 整体布局（保持与原先一致） */
/* -------------------- */
.home-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 24px;
  box-sizing: border-box;
  overflow: hidden;
}

/* 解析结果预览整体 */
.preview-area {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding-right: 8px;
}

/* 选项卡导航样式 */
.tab-nav {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 10px;
}
.tab-item {
  padding: 8px 16px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  white-space: nowrap;
}
.tab-item.active {
  color: #303133;
  font-weight: 500;
  border-bottom: 2px solid #409eff;
}

/* 各部分标题 */
.preview-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.section-title {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 600;
  color: #333333;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 4px;
}

/* 空提示 */
.empty-message {
  font-size: 0.95rem;
  color: #888888;
  padding: 8px 12px;
  background-color: #fafafa;
  border-radius: 4px;
}

/* 表格公共样式 */
.table-wrapper {
  overflow-x: auto;
}
.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.95rem;
}
.data-table thead th {
  background-color: #f5f7fa;
  color: #333333;
  font-weight: 600;
  padding: 10px 14px;
  border-bottom: 2px solid #e0e0e0;
  text-align: center;
}
.data-table tbody td {
  padding: 10px 14px;
  border-bottom: 1px solid #eaeaea;
  text-align: center;
}

.type-group {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  padding: 12px;
}
.type-header {
  font-size: 1rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}
.scroll-container {
  max-height: 200px;
  overflow-y: auto;
}
.history-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.problem-item {
  padding: 12px;
  border-radius: 6px;
  background-color: #fafafa;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
.problem-header {
  display: flex;
  justify-content: space-between;
  padding-bottom: 8px;
  margin-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}
.acc-person,
.acc-date {
  font-size: 14px;
  color: #606266;
}
.problem-content {
  font-size: 15px;
  color: #333;
  line-height: 1.5;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.preview-area::-webkit-scrollbar {
  width: 6px;
}
.preview-area::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}
.scroll-container::-webkit-scrollbar {
  width: 6px;
}
.scroll-container::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}
</style>